package com.lottery.game.controller.v2.bettingsecord;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lottery.game.annotation.Current;
import com.lottery.game.common.BasePage;
import com.lottery.game.common.Response;
import com.lottery.game.common.constants.GlobalLotteryConstants;
import com.lottery.game.common.utils.StringUtil;
import com.lottery.game.constants.RespErrorCodes;
import com.lottery.game.controller.v2.bettingsecord.request.UserBetsRequest;
import com.lottery.game.controller.v2.bettingsecord.response.SysDictBets;
import com.lottery.game.core.model.dto.UserToken;
import com.lottery.game.core.modules.entity.app.BetRecordTD;
import com.lottery.game.core.modules.entity.app.BetRecordVO;
import com.lottery.game.core.modules.entity.game.SysDict;
import com.lottery.game.core.modules.entity.user.GameBets;
import com.lottery.game.core.modules.entity.user.GameUserMoneyChange;
import com.lottery.game.core.modules.mapper.GameUserMoneyChangeDao;
import com.lottery.game.core.modules.service.app.BetService;
import com.lottery.game.core.modules.service.app.GameBetService;
import com.lottery.game.core.modules.service.app.UpAndDownReportService;
import com.lottery.game.core.modules.service.app.v2.BetRecordService;
import com.lottery.game.core.modules.service.game.GameTypePlayingRelationService;
import com.lottery.game.core.modules.service.game.SysDictService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController
@RequestMapping(value = "/api/v2/user/bettingsecord")
@Api(tags = "APP-个人中心")
public class BetRecordController {

    @Autowired
    private GameBetService gameBetsService;
    @Autowired
    private GameUserMoneyChangeDao gameUserMoneyChangeDao;
    @Autowired
    private BetRecordService betRecordService;
    @Autowired
    private BetService betService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private UpAndDownReportService upAndDownReportService;
    @Autowired
    private GameTypePlayingRelationService gameTypePlayingRelationService;



    @SuppressWarnings("unchecked")
    @ApiOperation(value = "投注记录", notes = "投注记录(调用彩票种类API)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ticket", value = "令牌ticket", dataType = "String", paramType = "header",required = true),
    })
    @PostMapping(value = "/findUserBetList", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public Response<PageInfo<GameBets>> findUserBetList(@ApiIgnore @Current UserToken userToken, @RequestBody BasePage<UserBetsRequest> param) {

        try {
            if (param.getPage() == null || param.getPage() == 0 || param.getRows() == null || param.getRows() == 0) {
                return Response.buildError(RespErrorCodes.PARAM_PAGE_INVALID_ERROR.getErrorMsg());
            }
            //设置不能为null,防止报错
            UserBetsRequest data = param.getData();
            if (null == data){
                data = new UserBetsRequest();
            }
            //暂时设置为下注和扯注 派彩
            String betType = "cancelBet,bet,bonus";
            PageHelper.startPage(param.getPage(), param.getRows());
            PageInfo<GameBets> list = new PageInfo<>(gameBetsService.queryGameBetsForRoomByTickTypeLast(userToken.getId(), param.getStartDate(),
                    param.getEndDate(),data.getGameTypePlayingTicket(),data.getStatus(),betType));
            //判断不为空
            List<GameBets> gameBetsList = list.getList();
            //下注总额
            BigDecimal betSum = new BigDecimal("0");
            //奖金
            BigDecimal bonusSum = new BigDecimal("0");
            if (!CollectionUtils.isEmpty(gameBetsList)){
                Example example = new Example(SysDict.class);
                Example.Criteria criteria = example.createCriteria();
                //默认升序
                example.setOrderByClause("sort ASC");
                criteria.andEqualTo("type",GlobalLotteryConstants.TICKET_TYPE);
                //查询
                List<SysDict> sysDictList = sysDictService.selectByExample(example);

                for (GameBets bets : gameBetsList) {
                    if (StringUtil.isEmpty(bets.getStatus())){
                        bets.setStatus("0");
                    }
                    bets.setBetStrContext(this.getTempStrBet(bets));
                    bets.setTemaStr(this.getTempStrTema(bets));
                    for (SysDict sysDict : sysDictList) {
                        if (bets.getGameTypeTicket().equalsIgnoreCase(sysDict.getValue())) {
                            bets.setGameTypeTicketContent(sysDict.getLabel());
                        }
                    }
                    //通过id
                    String betsId = bets.getId();
                    List<GameUserMoneyChange> userMoneyChangeList = gameUserMoneyChangeDao.findUserList(betsId);
                    //判断是否为空，一般而言不能为空
                    if (!CollectionUtils.isEmpty(userMoneyChangeList)  ){
                        if (userMoneyChangeList.size() > 1 ){
                            for (GameUserMoneyChange moneyChange : userMoneyChangeList) {
                                //奖金
                                if ( "bonus".equalsIgnoreCase(moneyChange.getBetType()) ){
                                    BigDecimal bonusTemp = new BigDecimal(moneyChange.getChangeamt());
                                    bets.setBetType(moneyChange.getBetType());
                                    bets.setBonus(bonusTemp);
                                    bets.setResultblnc(moneyChange.getResultblnc());
                                    bonusSum = bonusSum.add(bonusTemp);
                                    //取消下注
                                }else if ("cancelBet".equalsIgnoreCase(moneyChange.getBetType())){
                                    bets.setBetType(moneyChange.getBetType());
                                    bets.setBonus(new BigDecimal(moneyChange.getChangeamt()));
                                    bets.setResultblnc(moneyChange.getResultblnc());
                                }
                            }
                        }else {
                            for (GameUserMoneyChange moneyChange : userMoneyChangeList) {
                                //下注
                                if ( "bet".equalsIgnoreCase(moneyChange.getBetType()) ){
                                    bets.setBetType(moneyChange.getBetType());
                                    BigDecimal betSumTemp = new BigDecimal(moneyChange.getChangeamt());
                                    bets.setBonus(betSumTemp);
                                    bets.setResultblnc(moneyChange.getResultblnc());
                                    betSum = betSum.add(betSumTemp);
                                }
                            }
                        }
                    }
                }
               /* String s = betSum.toString();
                if (!s.startsWith("-")){
                    s = "-"+s;
                }
                vo.setBetSum(s);
                vo.setBonusSum("+"+bonusSum);
                //盈利
                String sum = "";
                if (bonusSum.abs().compareTo(betSum.abs()) != -1){
                    BigDecimal subtract = bonusSum.abs().subtract(betSum.abs());
                    sum = "+" + subtract;
                }else {
                    BigDecimal subtract = betSum.abs().subtract(bonusSum.abs());
                    sum = "-" + subtract;
                }
                vo.setTotalSum(sum);
                vo.setPageInfo(list);*/
            }
            return Response.build(list);

        } catch (Exception e) {
            log.error("获取用户下注列表发生错误", e);
            return Response.buildError(RespErrorCodes.UNKNOWN_ERROR.getErrorMsg());
        }
    }


    @SuppressWarnings("unchecked")
    @ApiOperation(value = "彩票种类API", notes = "查询 \"投注记录\" 的前提")
    @GetMapping(value = "/getTickType", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public Response<Map<String,List>> getTickType() {
        try {
            //创建条件
            List<SysDictBets> list = new ArrayList<>();
            SysDictBets sysDictBets;
            //查询
            List<SysDict> sysDictList = gameTypePlayingRelationService.getGroup();
            if (!CollectionUtils.isEmpty(sysDictList)){
                SysDictBets dictBets = new SysDictBets();
                dictBets.setLabel("全部");
                dictBets.setValue("");
                list.add(dictBets);
                for (SysDict sysDict : sysDictList) {
                    sysDictBets = new SysDictBets();
                    BeanUtils.copyProperties(sysDict,sysDictBets);
                    list.add(sysDictBets);
                }
            }
            List<SysDictBets> statusList = new ArrayList<>();

            //暂时写死,后期字典表0待开奖 1封盘状态，2已开奖完成，-1开奖异常  已中奖 未中奖 待开奖  撤单 和局
            String[] stringArray = {"全部状态", "待开奖",  "已中奖", "撤单","和局","未中奖"};
            String[] stringsArray = {"", "0", "2", "3", "4","-9"};
            SysDictBets sysDict;
            for (int i = 0; i < stringArray.length; i++) {
                sysDict = new SysDictBets();
                sysDict.setLabel(stringArray[i]);
                sysDict.setValue(stringsArray[i]);
                statusList.add(sysDict);
            }
            Map<String,List> map  = new HashMap<>();
            map.put("tickType",list);
            map.put("status",statusList);
            return Response.build(map);

        } catch (Exception e) {
            log.error("获取彩票种类API发生错误", e);
            return Response.buildError(RespErrorCodes.UNKNOWN_ERROR.getErrorMsg());
        }
    }


    @SuppressWarnings("unchecked")
    @ApiOperation(value = "投注记录统计", notes = "根据时间统计(count：下注次数；betSum：下注总和；bonusSum：奖金)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ticket", value = "令牌ticket", dataType = "String", paramType = "header",required = true),
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String",required = true,example = "2019-05-22 00:00:00"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", required = true,example = "2019-05-22 23:59:59"),
    })
    @GetMapping(value = "/getSum", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public Response<Map<String,List>> getSum(@ApiIgnore @Current UserToken userToken, @RequestParam(value = "startDate") String startDate,
                                             @RequestParam(value = "endDate") String endDate) {
        try {

            Map<String, Object> map = getService().getBetSum(userToken.getId(), startDate, endDate);
            BigDecimal bonusSum = new BigDecimal(String.valueOf(map.get("bonusSum"))).setScale(1,BigDecimal.ROUND_DOWN);
            BigDecimal betSum = new BigDecimal(String.valueOf(map.get("betSum"))).setScale(1,BigDecimal.ROUND_DOWN);
            BigDecimal betStatusSum = new BigDecimal(String.valueOf(map.get("betStatusSum"))).setScale(1,BigDecimal.ROUND_DOWN);
            map.put("bonusSum",bonusSum.subtract(betSum));
            map.put("betSum",betSum);
            return Response.build(map);

        } catch (Exception e) {
            log.error("投注记录统计发送错误", e);
            return Response.buildError(RespErrorCodes.UNKNOWN_ERROR.getErrorMsg());
        }
    }

    @SuppressWarnings("unchecked")
    @ApiOperation(value = "交易记录详情页面", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "类型（bet,bonus,cancelBet,1,2）", dataType = "String", required = true,example = "bonus"),
            @ApiImplicitParam(name = "gameBetsId", value = "id", dataType = "String", required = true,example = "2f6fbd00f97a41ad94ca42e8c2eb8a1f"),
    })
    @GetMapping(value = "/getPageInfo", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public Response<Object> getPageInfo(@RequestParam(value = "title") String title,@RequestParam(value = "gameBetsId")String gameBetsId) {
        try {
            //通过类型和ID查询详情信息
            return Response.build(getService().getPageInfo(title,gameBetsId));

        } catch (Exception e) {
            log.error("交易记录详情页面发送错误", e);
            return Response.buildError(RespErrorCodes.UNKNOWN_ERROR.getErrorMsg());
        }
    }

    @SuppressWarnings("unchecked")
    @ApiOperation(value = "交易记录", notes = "先查询 \"交易记录字典表API\" 得到字典信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ticket", value = "令牌ticket", dataType = "String", paramType = "header",required = true),
    })
    @PostMapping(value = "/findUserAccountList", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public Response<PageInfo<BetRecordVO>> findUserAccountList(@ApiIgnore @Current UserToken userToken, @RequestBody BasePage<BetRecordTD> param) {
        try {
            //通过个人查询交易记录(包括充值[支付宝,微信]和下注撤单其他)
            BetRecordTD data = param.getData();
            String betType = data.getBetType();
            String recordStatus = data.getRecordStatus();
            //分页查询
            PageInfo<BetRecordVO> recodeList = getService().findRecodeList(userToken.getId(), param.getRows(), param.getPage(),
                    param.getEndDate(),param.getStartDate(), betType,recordStatus);
            List<BetRecordVO> list = recodeList.getList();
            //判断是否为空
            if(!CollectionUtils.isEmpty(list)){
                String[] stringArray = {"activity_week_bet_bonus", "songfen", "activity_first_charge", "return", "cancelBet", "bonus", "huishui", "agentBonus", "dividend", "supplement", "1"};
                //对金额做+ -处理,根据上面的数组,后期可以考虑写入到字典表或者配置表
                for (BetRecordVO recordVO : list) {
                    BigDecimal amount = recordVO.getAmount();
                    if (amount.compareTo(new BigDecimal("0")) == -1){
                        amount = amount.abs();
                    }
                    for (String s : stringArray) {
                        if (s.equals(recordVO.getTitle())) {
                            recordVO.setMoney("+"+ amount);
                            break;
                        }else {
                            recordVO.setMoney("-"+ amount);
                        }
                    }
                }
            }
            return Response.build(recodeList);

        } catch (Exception e) {
            log.error("获取交易记录列表发生错误", e);
            return Response.buildError(RespErrorCodes.UNKNOWN_ERROR.getErrorMsg());
        }
    }

    @SuppressWarnings("unchecked")
    @ApiOperation(value = "交易记录字典表API", notes = "查询 \"交易记录\" 的前提")
    @GetMapping(value = "/getSysAccountList", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public Response<Map<String,List>> getSysAccountList() {
        try {
            List<SysDictBets> betTypelist = new ArrayList<>();
            SysDictBets sysDictBets ;
            List<SysDictBets> statusList = new ArrayList<>();

            //暂时写死,后期字典表 0:处理中,1:已完成,2:拒绝
            //状态
            String[] stringArray1 = {"全部状态", "处理中", "已完成",};
            String[] intArray1 = {"", "0", "1"};
            String[] stringArray2 = {"全部类型", "充值", "提现", "投注", "撤单", "奖金", "补分", "扣分", "送分", "回水", "周打码彩金", "返还", "新用户首充优惠", "返利", "代理分红"};
            String[] intArray2 = {"", "1", "2", "bet", "cancelBet", "bonus", "supplement", "koufeng", "songfen", "huishui", "activity_week_bet_bonus", "return", "activity_first_charge", "agentBonus", "dividend",};
            SysDictBets sysDict;
            for (int i = 0; i < stringArray1.length; i++) {
                sysDict = new SysDictBets();
                sysDict.setLabel(stringArray1[i]);
                sysDict.setValue(intArray1[i]);
                statusList.add(sysDict);
            }
            for (int i = 0; i < stringArray2.length; i++) {
                sysDict = new SysDictBets();
                sysDict.setLabel(stringArray2[i]);
                sysDict.setValue(intArray2[i]);
                betTypelist.add(sysDict);
            }
            Map<String,List> map  = new HashMap<>();
            map.put("betType",betTypelist);
            map.put("status",statusList);
            return Response.build(map);

        } catch (Exception e) {
            log.error("交易记录字典表API发送错误", e);
            return Response.buildError(RespErrorCodes.UNKNOWN_ERROR.getErrorMsg());
        }
    }
    public BetRecordService getService(){
        return betRecordService;
    }


    /**
     * @Description 英文转中文，betStr
     * @param:
     * @Return
     * @Date 2019/5/12_13:53
     */
    private String getTempStrBet(GameBets bets) {
        String str = "";
        switch (bets.getBetStr()){
            case "da":
                str = "大";
                break;
            case "xiao":
                str = "小";
                break;
            case "dan":
                str = "单";
                break;
            case "shuang":
                str = "双";
                break;
            case "dadan":
                str = "大单";
                break;
            case "dashuang":
                str = "大双";
                break;
            case "xiaodan":
                str = "小单";
                break;
            case "jida":
                str = "极大";
                break;
            case "jixiao":
                str = "极小";
                break;
            case "hongbo":
                str = "洪波";
                break;
            case "lanbo":
                str = "蓝波";
                break;
            case "lvbo":
                str = "绿波";
                break;
            case "baozi":
                str = "豹子";
                break;
            case "shunzi":
                str = "顺子";
                break;
            case "duizi":
                str = "对子";
                break;
            default:
                str = "";
        }
        return str;
    }

    /**
     * @Description 整合特码系列参数，方便前端对接
     * @param:
     * @Return
     * @Date 2019/5/7_14:05
     */
    private String getTempStrTema(GameBets gameBets) {
        StringBuffer sbStr = new StringBuffer();
        if (null !=  gameBets.getTema0()){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema0())
                    .append(",");
        }
        if (null != gameBets.getTema1()){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema1())
                    .append(",");
        }
        if (null != (gameBets.getTema2())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema2())
                    .append(",");
        }
        if (null != (gameBets.getTema3())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema3())
                    .append(",");
        }
        if (null != (gameBets.getTema4())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema4())
                    .append(",");
        }
        if (null != (gameBets.getTema5())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema5())
                    .append(",");
        }
        if (null != (gameBets.getTema6())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema6())
                    .append(",");
        }
        if (null != (gameBets.getTema7())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema7())
                    .append(",");
        }
        if (null != (gameBets.getTema8())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema8())
                    .append(",");
        }
        if (null != (gameBets.getTema9())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema9())
                    .append(",");
        }
        if (null != (gameBets.getTema10())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema10())
                    .append(",");
        }
        if (null != (gameBets.getTema11())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema11())
                    .append(",");
        }
        if (null != (gameBets.getTema12())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema12())
                    .append(",");
        }
        if (null != (gameBets.getTema13())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema13())
                    .append(",");
        }
        if (null != (gameBets.getTema14())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema14())
                    .append(",");
        }
        if (null != (gameBets.getTema15())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema15())
                    .append(",");
        }
        if (null != (gameBets.getTema16())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema16())
                    .append(",");
        }
        if (null != (gameBets.getTema17())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema17())
                    .append(",");
        }
        if (null != (gameBets.getTema18())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema18())
                    .append(",");
        }
        if (null != (gameBets.getTema19())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema19())
                    .append(",");
        }
        if (null != (gameBets.getTema20())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema20())
                    .append(",");
        }
        if (null != (gameBets.getTema21())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema21())
                    .append(",");
        }if (null != (gameBets.getTema22())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema22())
                    .append(",");
        }if (null != (gameBets.getTema23())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema23())
                    .append(",");
        }
        if (null != (gameBets.getTema24())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema24())
                    .append(",");
        }
        if (null != gameBets.getTema25()){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema25())
                    .append(",");
        }
        if (null != (gameBets.getTema26())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema26())
                    .append(",");
        }
        if (null != (gameBets.getTema27())){
            sbStr
                    .append("特码:")
                    .append(gameBets.getTema27())
                    .append(",");
        }
        String resultStr = sbStr.toString();
        int i = resultStr.lastIndexOf(",");
        //没匹配到
        if (i != GlobalLotteryConstants.RES_ERROR){
            resultStr = resultStr.substring(0, i);
        }else {
            resultStr = "特码: 无";
        }
        return resultStr;
    }

}
